<template>
  <div id="app">
    <van-nav-bar title="配置中心" class="nav-title" />
    <van-form @submit="onSubmit">
      <!-- 水情配置 -->
      <van-field
        readonly
        clickable
        name="picker"
        label="水情配置"
        @click="waterRegimenPopupVisible = true"
      >
        <template #input>
          <ul v-if="selectedWaterTexts.length">
            <li v-for="(item,index) in selectedWaterTexts" :key="index">{{ item }}</li>
          </ul>
          <span v-else class="placeholder">暂无</span>
        </template>
      </van-field>
      <van-popup v-model="waterRegimenPopupVisible" position="bottom">
        <van-tree-select
          :items="waterRegimenItems"
          :active-id.sync="waterRegimenActiveIds"
          :main-active-index.sync="waterRegimenActiveIndex"
        />
      </van-popup>

      <!-- 航道配置 -->
      <van-field
        readonly
        clickable
        name="picker"
        label="航道配置"
        @click="channelSectionsPopupVisible = true"
      >
        <template #input>
          <ul v-if="selectedChannelSectionsTexts.length">
            <li v-for="(item,index) in selectedChannelSectionsTexts" :key="index">{{ item }}</li>
          </ul>
          <span v-else class="placeholder">暂无</span>
        </template>
      </van-field>
      <van-popup v-model="channelSectionsPopupVisible" position="bottom">
        <van-tree-select
          :items="channelSectionsItems"
          :active-id.sync="channelSectionsActiveIds"
          :main-active-index.sync="channelSectionsActiveIndex"
        />
      </van-popup>

      <!-- 公告推送地区 -->
      <van-field
        readonly
        clickable
        name="picker"
        label="公告推送地区"
        placeholder="请选择"
        @click="noticeRegionsPopupVisible = true"
      >
        <template #input>
          <ul v-if="selectedNoticeRegionsTexts.length">
            <li v-for="(item,index) in selectedNoticeRegionsTexts" :key="index">{{ item }}</li>
          </ul>
          <span v-else class="placeholder">暂无</span>
        </template>
      </van-field>
      <van-popup v-model="noticeRegionsPopupVisible" position="bottom">
        <van-tree-select
          :items="noticeRegionsItems"
          :active-id.sync="noticeRegionsActiveIds"
          :main-active-index.sync="noticeRegionsActiveIndex"
        />
      </van-popup>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" color="#1a2980">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getPushConfigQuery, getPushConfigSubmit, getUserIdByCode } from '@/api/mobile/index'

export default {
  name: 'Config',
  data() {
    return {
      userId: null,
      // 水情配置
      waterRegimenPopupVisible: false,
      waterRegimenItems: [],
      waterRegimenActiveIds: [],
      waterRegimenActiveIndex: 0,
      // 航道配置
      channelSectionsPopupVisible: false,
      channelSectionsItems: [],
      channelSectionsActiveIds: [],
      channelSectionsActiveIndex: 0,
      // 公告
      noticeRegionsPopupVisible: false,
      noticeRegionsItems: [],
      noticeRegionsActiveIds: [],
      noticeRegionsActiveIndex: 0
    }
  },
  computed: {
    // 已选择水情配置
    selectedWaterTexts() {
      const result = []
      // 遍历所有城市分组
      this.waterRegimenItems.forEach(cityGroup => {
        cityGroup.children.forEach(site => {
          if (this.waterRegimenActiveIds.includes(site.id)) {
            result.push(site.text)
          }
        })
      })
      return result
    },
    // 已选择航道配置
    selectedChannelSectionsTexts() {
      const result = []
      this.channelSectionsItems.forEach(cityGroup => {
        cityGroup.children.forEach(site => {
          if (this.channelSectionsActiveIds.includes(site.id)) {
            result.push(site.text)
          }
        })
      })
      return result
    },
    // 已选择公告配置
    selectedNoticeRegionsTexts() {
      const result = []
      this.noticeRegionsItems.forEach(cityGroup => {
        cityGroup.children.forEach(site => {
          if (this.noticeRegionsActiveIds.includes(site.id)) {
            result.push(site.text)
          }
        })
      })
      return result
    }
  },
  async mounted() {
    // 从 URL 获取 code
    const urlParams = new URLSearchParams(window.location.search)
    const code = urlParams.get('code')
    // const code = "021vj010037lvU1v9w000eEqhC4vj01S";
    debugger
    console.log('code1:', code)
    if (!code) {
      // 如果没有 code，跳转到授权页
      window.location.href = '/wechat-auth'
      return
    }
    console.log('code2:', code)

    try {
      // 调用接口获取 userId
      const userIdRes = await getUserIdByCode({ code: code })
      const userId = userIdRes
      console.log('userId:', userId)
      // 存储 userId 到 data 或 vuex 中供后续使用
      this.userId = userId

      // 初始化页面数据
      this.initPage(userId)
    } catch (error) {
      console.error('获取 userId 失败:', error)
      Toast.fail('授权失败，请重试')
    }
    // this.initPage()
  },
  methods: {
    getChosenIds(noticeData) {
      const chosenIds = []
      for (const city in noticeData) {
        if (noticeData.hasOwnProperty(city)) {
          noticeData[city].forEach(item => {
            if (item.isChose === '1') {
              chosenIds.push(item.id)
            }
          })
        }
      }
      return chosenIds
    },
    transformToTree(regimenData) {
      const result = []
      for (const city in regimenData) {
        if (regimenData.hasOwnProperty(city)) {
          const citySites = regimenData[city]
          const cityNode = {
            text: city,
            children: []
          }
          citySites.forEach(site => {
            cityNode.children.push({
              text: site.name,
              id: site.id
            })
          })

          result.push(cityNode)
        }
      }

      return result
    },
    // 初始化页面
    async initPage(userId) {
      const res = await getPushConfigQuery({ userId })
      this.waterRegimenItems = this.transformToTree(res.regimen)
      this.waterRegimenActiveIds = this.getChosenIds(res.regimen)

      this.channelSectionsItems = this.transformToTree(res.scale)
      this.channelSectionsActiveIds = this.getChosenIds(res.scale)

      this.noticeRegionsItems = this.transformToTree(res.notice)
      this.noticeRegionsActiveIds = this.getChosenIds(res.notice)
    },
    async onSubmit() {
      console.log(this.waterRegimenActiveIds)
      console.log(this.channelSectionsActiveIds)
      console.log(this.noticeRegionsActiveIds)
      const params = {
        userId: this.userId,
        configList: [
          ...this.waterRegimenActiveIds.map(el => {
            return { id: el, type: '水情信息' }
          }),
          ...this.channelSectionsActiveIds.map(el => {
            return { id: el, type: '航道信息' }
          }),
          ...this.noticeRegionsActiveIds.map(el => {
            return { id: el, type: '通知公告' }
          })
        ]
      }
      const res = await getPushConfigSubmit(params)
      console.log('提交配置:', params, '结果:', res)
      Toast.success('配置提交成功')
    }

  }
}
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.placeholder{
  color: #969799;
  text-align: right;
}
.van-nav-bar__title{
  font-weight: bold;
  margin-bottom: 12px;
  line-height: 1.4;
  color: #1a2980;
}
</style>
